/*
 * PhotoandVideoViewController
 * @description 本文件提供继承MWPhotoBrowser的照片视频放大展示界面
 * @package
 * @author 		yinlinlin
 * @copyright
 * @version 		1.0
 * @description 本文件提供继承MWPhotoBrowser的照片视频放大展示界面
 */


#import "PhotoandVideoViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "CustomStatueBar.h"
#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import "MBProgressHUD.h"
#import "QuadCurveMenu.h"
#import "BanBu_UMengShareManager.h"
@interface PhotoandVideoViewController ()<MBProgressHUDDelegate,QuadCurveMenuDelegate>
{
    MPMoviePlayerController *moviePlayer;
    //zyfzyfzyf⬇️
    QuadCurveMenu *_menu;
    MBProgressHUD *_hud;
    //zyfzyfzyf⬆️
}
@end

@implementation PhotoandVideoViewController
@synthesize album_Model = _album_Model;
- (void)dealloc
{
    [_shortUrl release];_shortUrl = nil;
    if (_page)
    {
        [_page release];
        _page = nil;
    }
    if (_audioManager)
    {
        [_audioManager release];
        _audioManager = nil;
    }
    [_currentPhoto_id release];
    _currentPhoto_id = nil;
    [_album_Model release];
    _album_Model = nil;
    [super dealloc];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //20141020
    //zyfzyfzyf⬇️
#warning 没有国际化
    _shortUrl=[[NSMutableString alloc]init];
    NSString *langauage=[MyAppDataManager getPreferredLanguage];
    if ([langauage isEqualToString:@"zh-Hans"]) {
        //sina
        QuadCurveMenuItem *sinaMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_sina_icon.png"] withIntro:NSLocalizedString(@"sinaPlatform", nil)];
        // tencentWeibo
        QuadCurveMenuItem *tencentMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_tencent_icon.png"] withIntro:NSLocalizedString(@"tencentPlatform", nil)];
        
        // qzone
        QuadCurveMenuItem *qzoneMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_qzone_icon.png"] withIntro:NSLocalizedString(@"qqZonePlatform", nil)];
        //wechatLine
        QuadCurveMenuItem *weLineMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_wechat_timeline_icon.png"] withIntro:NSLocalizedString(@"wechatTimelinePlatform", nil)];
        // wechatSession
        QuadCurveMenuItem *weSessionMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_wechat_session_icon.png"] withIntro:NSLocalizedString(@"wechatSessionPlatform", nil)];
        // renren
        QuadCurveMenuItem *renrenMenuItem= [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_renren_icon.png"] withIntro:NSLocalizedString(@"renrenPlatForm", nil)];
        
        //facebook
        QuadCurveMenuItem *FacebookMenuItem= [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_facebook_icon.png"] withIntro:@"Facebook"];
        //twitter
        QuadCurveMenuItem * TwitterItem= [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"UMS_twitter_icon.png"] withIntro:@"Twitter"];
        
        NSArray *menus = [NSArray arrayWithObjects:sinaMenuItem, tencentMenuItem, qzoneMenuItem, weLineMenuItem, weSessionMenuItem, renrenMenuItem,FacebookMenuItem,TwitterItem, nil];
        [FacebookMenuItem release];
        [TwitterItem release];        [sinaMenuItem release];
        [qzoneMenuItem release];
        [tencentMenuItem release];
        [weLineMenuItem release];
        [weSessionMenuItem release];
        [renrenMenuItem release];
        
        _menu = [[QuadCurveMenu alloc] initWithFrame:CGRectMake(0, 0, __MainScreen_Width, __MainScreen_Height +20) menus:menus withShare:YES];
        _menu.delegate = self;
        [self.view addSubview:_menu];
        
    }
    else
    {
        QuadCurveMenuItem *facebookMenuItem1 = [[QuadCurveMenuItem alloc] initWithCustomImage:nil withIntro:nil];
        facebookMenuItem1.userInteractionEnabled=NO;
        //facebook
        QuadCurveMenuItem *facebookMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"facebookForm.png"] withIntro:@"Facebook"];
        //twitter
        QuadCurveMenuItem *twitterMenuItem = [[QuadCurveMenuItem alloc] initWithCustomImage:[UIImage imageNamed:@"twitterForm.png"] withIntro:@"Twitter"];
        NSArray *menus = [NSArray arrayWithObjects:facebookMenuItem1,facebookMenuItem,facebookMenuItem1,facebookMenuItem1,twitterMenuItem, nil];
        [facebookMenuItem release];
        [twitterMenuItem release];
        _menu = [[QuadCurveMenu alloc] initWithFrame:CGRectMake(0, 0, __MainScreen_Width, __MainScreen_Height+20) menus:menus withShare:YES];
        _menu.delegate = self;
        [self.view addSubview:_menu];
        
    }
    //20141020
    //zyfzyfzyf⬆️
}

#pragma mark - 重写MWPhotoBrowser的方法,处理播放按钮的显示
/**
 * @函数名称：configurePage:forIndex:
 * @函数描述：重写MWPhotoBrowser的方法，处理视频的显示和播放
 * @输入参数：(MWZoomingScrollView *)page (NSUInteger)index
 * @输出参数：void
 * @返回值：void
 */
- (void)configurePage:(MWZoomingScrollView *)page forIndex:(NSUInteger)index
{
    page.frame = [self frameForPageAtIndex:index];
    page.tag = PAGE_INDEX_TAG_OFFSET + index;
    ALBUMFILETYPE tag = [self getTypeOfIndex:index withPage:page];
    if (tag == ALBUM_VIDEO)
    {
        page.hidePlayBu = NO;
        page.hideSoundPlay = YES;
        __block id bself = self;
        //点击播放按钮的回调
        [page setPlayPressedCallBack:^(BOOL play){
            [bself playBuPressed:page withPlay:play];
        }];
    }
    else if (tag == ALBUM_PHOTOWITHSOUND)
    {
        page.hideSoundPlay = NO;
        page.hidePlayBu = YES;
        [page.playImg stopAnimating];
        __block id bself = self;
        //点击语音播放按钮的回调
        [page setPlayPressedCallBack:^(BOOL play){
            [bself playBuPressed:page withPlay:play];
        }];
        
    }
    else
    {
        
        page.hidePlayBu = YES;
        page.hideSoundPlay = YES;
    }
    page.photo = [self photoAtIndex:index];
    
}

#pragma mark - 点击视频的播放按钮
/**
 * @函数名称：playBuPressed:
 * @函数描述：点击界面的播放按钮，开始加载网上视频资源
 * @输入参数：(MWZoomingScrollView *)page：添加播放按钮的界面
 * @输出参数：添加moviePlayer，播放视频
 * @返回值：void
 */

- (void)playBuPressed:(MWZoomingScrollView *)page withPlay:(BOOL)is_play
{
    BanBu_MediaModel * model = [self.delegate typeOfPhotosInPhotoBrowser:self photoAtIndex:_currentPageIndex];
    //照片加语音，播放语音
    if ([model.media_type isEqualToString:@"p"])
    {
        if(_audioManager)
        {
            [_audioManager stopPlay];
            [page.playImg stopAnimating];
            [_audioManager release];
            _audioManager = nil;
            if (!is_play)
            {
                return;
            }
        }
        if (_page)
        {
            [_page release];
            _page = nil;
        }
        _page = [page retain];
        _audioManager = [[RecordAudio alloc] init];
        _audioManager.delegate = self;
        // 判断语音评论是否已经下载
        NSString *fileName = model.intro_soundurl;
        _audioManager.audioSavePath = [AppComManager pathForMedia:fileName];
        //已经下载，直接播放
        if ([_audioManager startPlay])
        {
            NSLog(@"播放");
            [page.playImg startAnimating];
        }
        //未下载，下载语音
        else
        {
            NSString * audioPath = [AppComManager pathForMedia:model.intro_soundurl];
            
            if (![FileManager fileExistsAtPath:audioPath])
            {
                [AppComManager getBanBuMedia:model.intro_soundurl delegate:self];
                return;
            }
        }
        
    }
    else
    {
        MPMoviePlayerViewController *playerViewController =[[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL URLWithString:model.full_url]];
        //    MPMoviePlayerViewController *playerViewController =[[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL URLWithString:@"http://static.tripbe.com/videofiles/20121214/9533522808.f4v.mp4"]];
        //    MPMoviePlayerViewController *playerViewController =[[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL URLWithString:@"https://s3.amazonaws.com/houston_city_dev/video/h264-original/1/haku.mp4"]];
        
        //使用presentMoviePlayerViewControllerAnimated代替 [[playerViewController moviePlayer]play],[[playerViewController moviePlayer]play]播放完成之后，内存不减少
        [self presentMoviePlayerViewControllerAnimated:playerViewController];
        [playerViewController release];
        playerViewController = nil;
    }
}

#pragma mark - 获取当前页面文件类型：视频or照片
/**
 * @函数名称：getTypeOfIndex:
 * @函数描述：从代理中获取文件的类型，是图片还是视频，根据返回的类型判断是否需要隐藏播放按钮
 * @输入参数：(NSInteger)index：第几张图片
 * @输出参数：返回类型
 * @返回值：FILETAG，类型
 */
- (ALBUMFILETYPE)getTypeOfIndex:(NSInteger)index withPage:(MWZoomingScrollView *)page
{
    BanBu_MediaModel * model = [self.delegate typeOfPhotosInPhotoBrowser:self photoAtIndex:index];
    if (!_currentPhoto_id)
    {
        _currentPhoto_id = [[NSMutableString alloc]initWithCapacity:50];
    }
    [_currentPhoto_id setString:@""];
    [_currentPhoto_id appendString:model.photo_id];
    
    NSLog(@"intro_soundurl:%@",model.intro_soundurl);
    if ([model.media_type isEqualToString:@"p"])
    {
        //照片加语音
        if (model.intro_soundurl)
        {
            NSLog(@"%@",[NSString stringWithFormat:@"%@''",model.soundlen]);
            //            page.playSoundBu.titleLabel.text = [NSString stringWithFormat:@"%@''",model.soundlen];
            [page.playSoundBu setTitle:[NSString stringWithFormat:@"%@''",model.soundlen] forState:UIControlStateNormal];
            return ALBUM_PHOTOWITHSOUND;
        }
        //纯照片
        else
        {
            return ALBUM_PHOTO;
        }
    }
    //视频
    else
    {
        return ALBUM_VIDEO;
    }
    
}

/**
 * @函数名称：performLayout
 * @函数描述：重写MWPhotoBrowser的方法，该方法是定义图片浏览下方的_toolbar
 * @输入参数：void
 * @输出参数：void
 * @返回值：void
 */
- (void)performLayout
{
    
    // Setup
    _performingLayout = YES;
    NSUInteger numberOfPhotos = [self numberOfPhotos];
    
    // Setup pages
    [_visiblePages removeAllObjects];
    [_recycledPages removeAllObjects];
    
    // Navigation buttons
    if ([self.navigationController.viewControllers objectAtIndex:0] == self)
    {
        UIBarButtonItem *doneButton = [[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"returnButton", nil) style:UIBarButtonItemStyleBordered target:self action:@selector(doneButtonPressed:)] autorelease];
        // Set appearance
        if ([UIBarButtonItem respondsToSelector:@selector(appearance)]) {
            [doneButton setBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
            [doneButton setBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsLandscapePhone];
            [doneButton setBackgroundImage:nil forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
            [doneButton setBackgroundImage:nil forState:UIControlStateHighlighted barMetrics:UIBarMetricsLandscapePhone];
            [doneButton setTitleTextAttributes:[NSDictionary dictionary] forState:UIControlStateNormal];
            [doneButton setTitleTextAttributes:[NSDictionary dictionary] forState:UIControlStateHighlighted];
        }
        self.navigationItem.leftBarButtonItem = doneButton;
        
        
        //这是更多操作的按钮
        UIBarButtonItem *MoreButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ic_topbar_more.png"] style:UIBarButtonItemStylePlain target:self action:@selector(moreButtonItemPressed)] autorelease];
        // Set appearance
        
        if ([UIBarButtonItem respondsToSelector:@selector(appearance)]) {
            [MoreButtonItem setBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
            [MoreButtonItem setBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsLandscapePhone];
            [MoreButtonItem setBackgroundImage:nil forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
            [MoreButtonItem setBackgroundImage:nil forState:UIControlStateHighlighted barMetrics:UIBarMetricsLandscapePhone];
            [MoreButtonItem setTitleTextAttributes:[NSDictionary dictionary] forState:UIControlStateNormal];
            [MoreButtonItem setTitleTextAttributes:[NSDictionary dictionary] forState:UIControlStateHighlighted];
        }
        self.navigationItem.rightBarButtonItem = MoreButtonItem;
        
    }
    //    // Toolbar
    
    
    if (numberOfPhotos > 1 || _displayActionButton)
    {
        [self.view addSubview:_toolbar];
    }
    else
    {
        [_toolbar removeFromSuperview];
    }
    //    // Toolbar items & navigation
    //    UIBarButtonItem *fixedLeftSpace = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil] autorelease];
    //    fixedLeftSpace.width = 32; // To balance action button
    //    UIBarButtonItem *flexSpace = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease];
    //    NSMutableArray *items = [[NSMutableArray alloc] init];
    ////
    //    //添加评分的按钮
    //    UIBarButtonItem * gradeItem = [[UIBarButtonItem alloc] initWithTitle:@"评价" style:UIBarButtonItemStylePlain target:self action:@selector(gradeForthisPhoto)];
    //    [items addObject:gradeItem];
    //    if (_displayActionButton)
    //        [items addObject:fixedLeftSpace];
    //    [items addObject:flexSpace];
    //    [items addObject:flexSpace];
    //    [_toolbar setItems:items];
    //    [items release];
    [self updateNavigation];
    // Content offset
    _pagingScrollView.contentOffset = [self contentOffsetForPageAtIndex:_currentPageIndex];
    [self tilePages];
    _performingLayout = NO;
    
}



#pragma mark - Paging

- (void)tilePages
{
    
    // Calculate which pages should be visible
    // Ignore padding as paging bounces encroach on that
    // and lead to false page loads
    CGRect visibleBounds = _pagingScrollView.bounds;
    int iFirstIndex = (int)floorf((CGRectGetMinX(visibleBounds)+PADDING*2) / CGRectGetWidth(visibleBounds));
    int iLastIndex  = (int)floorf((CGRectGetMaxX(visibleBounds)-PADDING*2-1) / CGRectGetWidth(visibleBounds));
    if (iFirstIndex < 0) iFirstIndex = 0;
    if (iFirstIndex > [self numberOfPhotos] - 1) iFirstIndex = [self numberOfPhotos] - 1;
    if (iLastIndex < 0) iLastIndex = 0;
    if (iLastIndex > [self numberOfPhotos] - 1) iLastIndex = [self numberOfPhotos] - 1;
    
    // Recycle no longer needed pages
    NSInteger pageIndex;
    for (MWZoomingScrollView *page in _visiblePages) {
        pageIndex = PAGE_INDEX(page);
        if (pageIndex < (NSUInteger)iFirstIndex || pageIndex > (NSUInteger)iLastIndex) {
            [_recycledPages addObject:page];
            [page prepareForReuse];
            [page removeFromSuperview];
            MWLog(@"Removed page at index %i", PAGE_INDEX(page));
        }
    }
    [_visiblePages minusSet:_recycledPages];
    while (_recycledPages.count > 2) // Only keep 2 recycled pages
        [_recycledPages removeObject:[_recycledPages anyObject]];
    
    // Add missing pages
    for (NSUInteger index = (NSUInteger)iFirstIndex; index <= (NSUInteger)iLastIndex; index++) {
        if (![self isDisplayingPageForIndex:index]) {
            
            // Add new page
            MWZoomingScrollView *page = [self dequeueRecycledPage];
            if (!page) {
                page = [[[MWZoomingScrollView alloc] initWithPhotoBrowser:self] autorelease];
            }
            [self configurePage:page forIndex:index];
            [_visiblePages addObject:page];
            [_pagingScrollView addSubview:page];
            MWLog(@"Added page at index %i", index);
            
            // Add caption
            MWCaptionView *captionView = [self captionViewForPhotoAtIndex:index];
            captionView.frame = [self frameForCaptionView:captionView atIndex:index];
            //            CGRect  rect = captionView.frame;
            
            [_pagingScrollView addSubview:captionView];
            
            page.captionView = captionView;
            //            //语音播放按钮
            //            UIButton * _playSoundBu = [UIButton buttonWithType:UIButtonTypeCustom];
            //            [_playSoundBu setImageEdgeInsets:UIEdgeInsetsMake(28, 1.5, 28, 1.5)];
            //            [_playSoundBu setImage:[UIImage imageNamed:@"album_playSound.png"] forState:UIControlStateNormal];
            //            [_playSoundBu setFrame:CGRectMake(captionView.frame.origin.x + 100, captionView.frame.origin.y - 80, 100, 96)];
            //            CGRect rect2 = _playSoundBu.frame;
            //            [_pagingScrollView addSubview:_playSoundBu];
            
            [page.playSoundBu setFrame:CGRectMake(111.5, captionView.frame.origin.y - 40, 97, 40)];
            
        }
    }
    
}

#pragma mark -分享平台选择界面
/**
 * @函数名称：quadCurveMenu:didSelectIndex:
 * @函数描述：分享平台界面
 * @输入参数：(QuadCurveMenu *)menu (NSInteger)idx
 * @输出参数：void
 * @返回值：void
 * @author：your name
 */
//zyfzyfzyf⬇️
-(void)quadCurveMenu:(QuadCurveMenu *)menu didSelectIndex:(NSInteger)idx
{
    [_menu setExpanding:NO];
    
    _hud=[[MBProgressHUD alloc]initWithView:self.view];
    [self.view addSubview:_hud];
    _hud.labelText=NSLocalizedString(@"loadingNotice", nil);
    _hud.delegate=self;
    [_hud show:YES];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //20141020
        NSString *sayText=[NSString stringWithFormat:@"%@%@",NSLocalizedString(@"koochatComment", nil),_shortUrl];
        //20141020
        //     UIImage *shareImage=[self imageForPhoto:[self.delegate photoBrowser:self photoAtIndex:_currentPageIndex]];
        BanBu_MediaModel * model = [self.delegate typeOfPhotosInPhotoBrowser:self photoAtIndex:_currentPageIndex];
        NSString *urlStr=model.full_url;
        NSString *mediaType=model.media_type;
        UIImage * shareImg;
        if ([mediaType hasPrefix:@"p"]) {
            shareImg=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.full_url]]];
        }
        else
            shareImg=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.thumb_url]]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [_hud hide:YES];
            //20141020⬇️
            NSString *langauage=[MyAppDataManager getPreferredLanguage];
            if ([langauage isEqualToString:@"zh-Hans"]) {
                [[BanBu_UMengShareManager shareUMengManager] shareToPlatform:idx WithText:sayText WithImage:shareImg WithClickUrlStr:urlStr WithPerformVC:self];
            }
            else
            {
                if (idx==1) {
                    [[BanBu_UMengShareManager shareUMengManager] shareToPlatform:6 WithText:sayText WithImage:shareImg WithClickUrlStr:urlStr WithPerformVC:self];
                }
                else
                    [[BanBu_UMengShareManager shareUMengManager] shareToPlatform:7 WithText:sayText WithImage:shareImg WithClickUrlStr:urlStr WithPerformVC:self];
                
            }
            //20141020⬆️
            //  [shareImg release];
        });
        
    });
}

#pragma mark - HUDdelegate
-(void)hudWasHidden:(MBProgressHUD *)hud
{
    [hud removeFromSuperview];
    [hud release];
    hud=nil;
}
//zyfzyfzyf⬆️


#pragma mark - 点击navigationItem.rightBarButtonItem
- (void)moreButtonItemPressed
{
    id <MWPhoto> photo = [super photoAtIndex:_currentPageIndex];
    NSLog(@"%@",[photo underlyingImage]);
    
    
    //当前用户是相册所有人
    if ([_album_Model.user_id isEqualToString:MyAppDataManager.useruid])
    {
        BanBu_MediaModel * model = [self.delegate typeOfPhotosInPhotoBrowser:self photoAtIndex:_currentPageIndex];
        //修改：yinlinlin:2014/06/27,是图片并且已经通过审核才能设为头像
        //zyfzyfzyf 增加了分享按钮
        if (([model.media_type isEqualToString:@"p"]) && (model.audit))
        {
            UIActionSheet * action = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"shareButton", nil),NSLocalizedString(@"saveButton", nil),NSLocalizedString(@"deleteButton", nil),NSLocalizedString(@"setHeadImage", nil), nil];
            action.tag = 100;
            [action showInView:self.view];
            [action release];
        }
        else
        {//他人相册
            UIActionSheet * action = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"shareButton", nil),NSLocalizedString(@"saveButton", nil),NSLocalizedString(@"deleteButton", nil), nil];
            action.tag = 100;
            [action showInView:self.view];
            [action release];
        }
        
    }
    else
    {
        UIActionSheet * action = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"shareButton", nil),NSLocalizedString(@"saveButton", nil), nil];
        [action showInView:self.view];
        action.tag = 101;
        [action release];
    }
    
    return;
    if ([self numberOfPhotos] > 0 && [photo underlyingImage])
    {
        //当前用户是相册所有人
        if ([_album_Model.user_id isEqualToString:MyAppDataManager.useruid])
        {
            UIActionSheet * action = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"saveButton", nil),NSLocalizedString(@"deleteButton", nil), nil];
            action.tag = 100;
            [action showInView:self.view];
            [action release];
        }
        else
        {
            UIActionSheet * action = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"saveButton", nil), nil];
            [action showInView:self.view];
            action.tag = 101;
            [action release];
        }
        
    }
}
#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"点击的index:%d",buttonIndex);
    if (buttonIndex == actionSheet.cancelButtonIndex)
    {
        return;
    }
    
    //zyfzyfzyf⬇️
    //分享
    if (buttonIndex == 0) {
        [_menu setExpanding:YES];
        self.navigationController.navigationBar.alpha=0;
        BanBu_MediaModel * model = [self.delegate typeOfPhotosInPhotoBrowser:self photoAtIndex:_currentPageIndex];
        NSString * shareUrl = [NSString stringWithFormat:@"%@",model.full_url];
        [AppComManager getBanBuData:@"/_sys_dict/_get_short_url.php?jsonfrom=" par:[NSDictionary dictionaryWithObjectsAndKeys:shareUrl,@"url", nil] delegate:self];
    }
    //zyfzyfzyf⬆️
    
    //保存
    if (buttonIndex == 1)
    {
        if(!_assetLibrary){
            _assetLibrary = [[ALAssetsLibrary alloc]init];
        }
        __block PhotoandVideoViewController * bself = self;
        [_assetLibrary saveImage:[self imageForPhoto:[self.delegate photoBrowser:self photoAtIndex:_currentPageIndex]] toAlbum:NSLocalizedString(@"fristTitle", nil) completionBlock:^(NSURL *assetURL, NSError *error) {
            
            [TKLoadingView showTkloadingAddedTo:bself.view title:NSLocalizedString(@"savesucess", nil) activityAnimated:NO duration:0.5];
            
        } failureBlock:^(NSError *error) {
            
            [TKLoadingView showTkloadingAddedTo:bself.navigationController.view title:NSLocalizedString(@"savefail", nil) activityAnimated:NO duration:0.5];
        }];
        
        return;
    }
    //删除
    if (buttonIndex == 2)
    {
        NSMutableString * deleteList = [[[NSMutableString alloc]init]autorelease];
        [deleteList appendFormat:@"%@,",_currentPhoto_id];
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"loadingNotice", nil) activityAnimated:YES];
        NSDictionary *parDic = [NSDictionary dictionaryWithObjectsAndKeys:_album_Model.album_id,@"albumid",deleteList,@"photoidlist",nil];
        NSLog(@"要删除的照片的相关信息:%@",parDic);
        [AppComManager getBanBuData:BanBu_v2_Delete_Fileof_Albumid par:parDic delegate:self];
        return;
    }
    //设头像：修改2014/06/17
    if (buttonIndex == 3)
    {
        BanBu_MediaModel * setfaceModel = [self.delegate typeOfPhotosInPhotoBrowser:self photoAtIndex:_currentPageIndex];
        NSDictionary *parDic = [NSDictionary dictionaryWithObjectsAndKeys:_album_Model.album_id,@"albumid",setfaceModel.thumb_url,@"facefile",setfaceModel.full_url,@"facefull",nil];
        NSLog(@"要设为头像的相关信息:%@",parDic);
        [AppComManager getBanBuData:BanBu_v2_Set_UserFace par:parDic delegate:self];
        
    }
}


#pragma mark - 接口返回数据
- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    //20141020
    if ([[resDic valueForKey:@"fc"] isEqualToString:@"get_short_url"]) {
        _shortUrl=[resDic valueForKey:@"shorturl"];
        [_shortUrl retain];
    }
    //20141020
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:NO afterShow:0];
    if ([AppComManager respondsDic:resDic isFunctionData:BanBu_v2_Delete_Fileof_Albumid])
    {
        NSLog(@"删除相册中照片返回数据:%@",resDic);
        if([[resDic valueForKey:@"ok"] boolValue])
        {
            NSLog(@"删除照片成功");
            if (_deleteCallBack)
            {
                _deleteCallBack(_currentPageIndex,resDic);
            }
        }
    }
    else if([AppComManager respondsDic:resDic isFunctionData:BanBu_v2_Set_UserFace])
    {
        NSLog(@"设置头像返回数据:%@",resDic);
        if([[resDic valueForKey:@"ok"] boolValue])
        {
            NSLog(@"设置头像成功");
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"modifySucceed", nil) activityAnimated:NO duration:0.5];
            NSMutableDictionary *infoUpdata = [NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:MyAppDataManager.useruid]];
            BanBu_MediaModel * setfaceModel = [self.delegate typeOfPhotosInPhotoBrowser:self photoAtIndex:_currentPageIndex];
            
            [infoUpdata setValue:setfaceModel.thumb_url forKey:@"uface"];
            [UserDefaults setValue:infoUpdata forKey:MyAppDataManager.useruid];
            [UserDefaults synchronize];
        }
    }
    
}
#pragma mark - 返回按钮
- (void)doneButtonPressed:(id)sender
{
    //恢复ios7下状态栏显示文字的背景色
    if (IS_IOS_7)
    {
        NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:@"",@"color", nil];
        [[NSNotificationCenter defaultCenter]postNotificationName:kThemeDidChangeAndIOS7Notification object:dic];
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 评价按钮触发事件
/**
 * @函数名称：gradeForthisPhoto
 * @函数描述：用户点击评价按钮触发的事件
 * @输入参数：void
 * @输出参数：评分界面
 * @返回值：void
 */
- (void)gradeForthisPhoto
{
    NSLog(@"当前页面:%d",_currentPageIndex);
}


#pragma mark - RecordAudioDelegate(播放录音代理)


/**
 *	@brief	下载music回调
 *
 *	@param 	resDic 	返回值
 *	@param 	error 	错误
 */
- (void)banbuDownloadRequest:(NSDictionary *)resDic didFinishedWithError:(NSError *)error
{
    if([[resDic valueForKey:@"ok"]boolValue])
    {
        if (_audioManager)
        {
            [_audioManager startPlay];
            [_page.playImg startAnimating];
        }
        
    }
}


- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player
{
    NSLog(@"begin");
}
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer*)player error:(NSError *)error
{
    //解码错误执行的动作
    NSLog(@"%@",error);
}

-(void)recordAudioDidStopAnimation:(BOOL)flag
{
    NSLog(@"停止");
}

- (void)recordAudioDidFinishPlay:(BOOL)finish error:(NSError *)error
{
    NSLog(@"停止");
    [_page.playImg stopAnimating];
    [_page.playSoundBu setSelected:NO];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
